package logic

import (
	"context"
	"encoding/json"

	"googee/common/errorx"
	"googee/service/addrbook/api/internal/svc"
	"googee/service/addrbook/api/internal/types"
	"googee/service/addrbook/rpc/addrbook"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type DefaultLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDefaultLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DefaultLogic {
	return &DefaultLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DefaultLogic) Default(req *types.IdPathReq) (resp *types.BookReply, err error) {
	resp = &types.BookReply{}

	id, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, err
	}

	book, err := l.svcCtx.AddrBook.SetDefaultAddrBook(l.ctx, &addrbook.AddrIdRequest{
		Id:     int64(req.Id),
		UserId: id,
	})

	if err != nil {
		return nil, errorx.NewCodeErrorNoMsg(errorx.ADDRBOOK_ERROR + 1)
	}

	copier.Copy(&resp.Data, book)

	return
}
